﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace displaycongress_desktop
{
    public class Decoder
    {
        /*
         * Convert the given hexadecimal string to a byte array.
         */
        public static byte[] HexString2Bytes(String hexString)
        {
            //check for null
            if (hexString == null) return new byte[0];

            //get length
            int len = hexString.Length;
            if (len % 2 == 1) return new byte[0];
            int len_half = len / 2;

            //create a byte array
            byte[] bs = new byte[len_half];
            try
            {
                //convert the hexstring to bytes
                for (int i = 0; i != len_half; i++)
                {
                    bs[i] = (byte)int.Parse(hexString.Substring(i * 2, 2), System.Globalization.NumberStyles.HexNumber);
                }
            }
            catch (Exception ex) {}

            //return the byte array
            return bs;
        }

        /*
         * Decode the byte array back to it's original format.
         */
        public static byte[] decode(byte[] bytes)
        {
            byte[] result = new byte[bytes.Length];

            for (int i = 0; i < bytes.Length; i++)
            {
                int newByte = 0;

                for (int j = 0; j < 8; j++)
                {
                    newByte += (int)(!((bytes[i] & (byte)Math.Pow(2, j)) > 0) ? Math.Pow(2, j) : 0);
                }

                result[i] = (byte)newByte;
            }

            return result;
        }
    }
}
